{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Bayesian Networks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "author: Jacob Schreiber <br>\n",
    "contact: jmschreiber91@gmail.com"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Bayesian networks are a powerful inference tool, in which a set of variables are represented as nodes, and the lack of an edge represents a conditional independence statement between the two variables, and an edge represents a dependence between the two variables. One of the powerful components of a Bayesian network is the ability to infer the values of certain variables, given observed values for another set of variables. These are referred to as the 'hidden' and 'observed' variables respectively, and need not be set at the time the network is created. The same network can have a different set of variables be hidden or observed between two data points. The more values which are observed, the closer the inferred values will be to the truth.\n",
    "\n",
    "While Bayesian networks can have extremely complex emission probabilities, usually Gaussian or conditional Gaussian distributions, pomegranate currently supports only discrete Bayesian networks. Bayesian networks are explicitly turned into Factor Graphs when inference is done, wherein the Bayesian network is turned into a bipartite graph with all variables having marginal nodes on one side, and joint tables on the other."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sun Oct 21 2018 \n",
      "\n",
      "numpy 1.14.2\n",
      "scipy 1.0.0\n",
      "pomegranate 0.10.0\n",
      "\n",
      "compiler   : GCC 7.2.0\n",
      "system     : Linux\n",
      "release    : 4.15.0-36-generic\n",
      "machine    : x86_64\n",
      "processor  : x86_64\n",
      "CPU cores  : 4\n",
      "interpreter: 64bit\n"
     ]
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn; seaborn.set_style('whitegrid')\n",
    "import numpy\n",
    "\n",
    "from pomegranate import *\n",
    "\n",
    "numpy.random.seed(0)\n",
    "numpy.set_printoptions(suppress=True)\n",
    "\n",
    "%load_ext watermark\n",
    "%watermark -m -n -p numpy,scipy,pomegranate"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The Monty Hall Gameshow\n",
    "\n",
    "The Monty Hall problem arose from the gameshow <i>Let's Make a Deal</i>, where a guest had to choose which one of three doors had a prize behind it. The twist was that after the guest chose, the host, originally Monty Hall, would then open one of the doors the guest did not pick and ask if the guest wanted to switch which door they had picked. Initial inspection may lead you to believe that if there are only two doors left, there is a 50-50 chance of you picking the right one, and so there is no advantage one way or the other. However, it has been proven both through simulations and analytically that there is in fact a 66% chance of getting the prize if the guest switches their door, regardless of the door they initially went with.\n",
    "\n",
    "We can reproduce this result using Bayesian networks with three nodes, one for the guest, one for the prize, and one for the door Monty chooses to open. The door the guest initially chooses and the door the prize is behind are completely random processes across the three doors, but the door which Monty opens is dependent on both the door the guest chooses (it cannot be the door the guest chooses), and the door the prize is behind (it cannot be the door with the prize behind it).\n",
    "\n",
    "To create the Bayesian network in pomegranate, we first create the distributions which live in each node in the graph. For a discrete (aka categorical) bayesian network we use DiscreteDistribution objects for the root nodes and ConditionalProbabilityTable objects for the inner and leaf nodes. The columns in a ConditionalProbabilityTable correspond to the order in which the parents (the second argument) are specified, and the last column is the value the ConditionalProbabilityTable itself takes. In the case below, the first column corresponds to the value 'guest' takes, then the value 'prize' takes, and then the value that 'monty' takes. 'B', 'C', 'A' refers then to the probability that Monty reveals door 'A' given that the guest has chosen door 'B' and that the prize is actually behind door 'C', or P(Monty='A'|Guest='B', Prize='C')."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# The guests initial door selection is completely random\n",
    "guest = DiscreteDistribution({'A': 1./3, 'B': 1./3, 'C': 1./3})\n",
    "\n",
    "# The door the prize is behind is also completely random\n",
    "prize = DiscreteDistribution({'A': 1./3, 'B': 1./3, 'C': 1./3})\n",
    "\n",
    "    # Monty is dependent on both the guest and the prize. \n",
    "monty = ConditionalProbabilityTable(\n",
    "        [[ 'A', 'A', 'A', 0.0 ],\n",
    "         [ 'A', 'A', 'B', 0.5 ],\n",
    "         [ 'A', 'A', 'C', 0.5 ],\n",
    "         [ 'A', 'B', 'A', 0.0 ],\n",
    "         [ 'A', 'B', 'B', 0.0 ],\n",
    "         [ 'A', 'B', 'C', 1.0 ],\n",
    "         [ 'A', 'C', 'A', 0.0 ],\n",
    "         [ 'A', 'C', 'B', 1.0 ],\n",
    "         [ 'A', 'C', 'C', 0.0 ],\n",
    "         [ 'B', 'A', 'A', 0.0 ],\n",
    "         [ 'B', 'A', 'B', 0.0 ],\n",
    "         [ 'B', 'A', 'C', 1.0 ],\n",
    "         [ 'B', 'B', 'A', 0.5 ],\n",
    "         [ 'B', 'B', 'B', 0.0 ],\n",
    "         [ 'B', 'B', 'C', 0.5 ],\n",
    "         [ 'B', 'C', 'A', 1.0 ],\n",
    "         [ 'B', 'C', 'B', 0.0 ],\n",
    "         [ 'B', 'C', 'C', 0.0 ],\n",
    "         [ 'C', 'A', 'A', 0.0 ],\n",
    "         [ 'C', 'A', 'B', 1.0 ],\n",
    "         [ 'C', 'A', 'C', 0.0 ],\n",
    "         [ 'C', 'B', 'A', 1.0 ],\n",
    "         [ 'C', 'B', 'B', 0.0 ],\n",
    "         [ 'C', 'B', 'C', 0.0 ],\n",
    "         [ 'C', 'C', 'A', 0.5 ],\n",
    "         [ 'C', 'C', 'B', 0.5 ],\n",
    "         [ 'C', 'C', 'C', 0.0 ]], [guest, prize])  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we pass these distributions into state objects along with the name for the node."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# State objects hold both the distribution, and a high level name.\n",
    "s1 = State(guest, name=\"guest\")\n",
    "s2 = State(prize, name=\"prize\")\n",
    "s3 = State(monty, name=\"monty\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then we add the states to the network, exactly like we did when making a HMM. In the future, all matrices of data should have their columns organized in the same order that the states are added to the network. The way the states are added to the network makes no difference to it, and so you should add the states according to how the columns are organized in your data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Create the Bayesian network object with a useful name\n",
    "model = BayesianNetwork(\"Monty Hall Problem\")\n",
    "\n",
    "# Add the three states to the network \n",
    "model.add_states(s1, s2, s3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then we need to add edges to the model. The edges represent which states are parents of which other states. This is currently a bit redundant with passing in the distribution objects that are parents for each ConditionalProbabilityTable. For now edges are added from parent -> child by calling `model.add_edge(parent, child)`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Add edges which represent conditional dependencies, where the second node is \n",
    "# conditionally dependent on the first node (Monty is dependent on both guest and prize)\n",
    "model.add_edge(s1, s3)\n",
    "model.add_edge(s2, s3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Lastly, the model must be baked to finalize the internals. Since Bayesian networks use factor graphs for inference, an explicit factor graph is produced from the Bayesian network during the bake step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "model.bake()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Predicting Probabilities\n",
    "\n",
    "We can calculate probabilities of a sample under the Bayesian network in the same way that we can calculate probabilities under other models. In this case, let's calculate the probability that you initially said door A, that Monty then opened door B, but that the actual car was behind door C."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.11111111111111109"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.probability(['A', 'B', 'C'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "That seems in line with what we know, that there is a 1/9th probability of that happening. \n",
    "\n",
    "Next, let's look at an impossible situation. What is the probability of initially saying door A, that Monty opened door B, and that the car was actually behind door B."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.0"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.probability(['A', 'B', 'B'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The reason that situation is impossible is because Monty can't open a door that has the car behind it."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Performing Inference\n",
    "\n",
    "Perhaps the most powerful aspect of Bayesian networks is their ability to perform inference. Given any set of observed variables, including no observations, Bayesian networks can make predictions for all other variables. Obviously, the more variables that are observed, the more accurate the predictions will get of the remaining variables. \n",
    "\n",
    "pomegranate uses the loopy belief propagation algorithm to do inference. This is an approximate algorithm which can yield exact results in tree-like graphs, and in most other cases still yields good results. Inference on a Bayesian network consists of taking in observations for a subset of the variables and using that to infer the values that the other variables take. The most variables which are observed, the closer the inferred values will be to truth. One of the powers of Bayesian networks is that the set of observed and 'hidden' (or unobserved) variables does not need to be specified beforehand, and can change from sample to sample.\n",
    "\n",
    "We can run inference using the `predict_proba` method and passing in a dictionary of values, where the key is the name of the state and the value is the observed value for that state. If we don't supply any values, we get the marginal of the graph, which is just the frequency of each value for each variable over an infinite number of randomly drawn samples from the graph.\n",
    "\n",
    "Lets see what happens when we look at the marginal of the Monty hall network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([{\n",
       "    \"frozen\" :false,\n",
       "    \"dtype\" :\"str\",\n",
       "    \"class\" :\"Distribution\",\n",
       "    \"parameters\" :[\n",
       "        {\n",
       "            \"A\" :0.3333333333333333,\n",
       "            \"C\" :0.3333333333333333,\n",
       "            \"B\" :0.3333333333333333\n",
       "        }\n",
       "    ],\n",
       "    \"name\" :\"DiscreteDistribution\"\n",
       "},\n",
       "       {\n",
       "    \"frozen\" :false,\n",
       "    \"dtype\" :\"str\",\n",
       "    \"class\" :\"Distribution\",\n",
       "    \"parameters\" :[\n",
       "        {\n",
       "            \"A\" :0.3333333333333333,\n",
       "            \"C\" :0.3333333333333333,\n",
       "            \"B\" :0.3333333333333333\n",
       "        }\n",
       "    ],\n",
       "    \"name\" :\"DiscreteDistribution\"\n",
       "},\n",
       "       {\n",
       "    \"frozen\" :false,\n",
       "    \"dtype\" :\"str\",\n",
       "    \"class\" :\"Distribution\",\n",
       "    \"parameters\" :[\n",
       "        {\n",
       "            \"A\" :0.3333333333333333,\n",
       "            \"C\" :0.3333333333333333,\n",
       "            \"B\" :0.3333333333333333\n",
       "        }\n",
       "    ],\n",
       "    \"name\" :\"DiscreteDistribution\"\n",
       "}], dtype=object)"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.predict_proba({})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We are returned three `DiscreteDistribution` objects, each representing the marginal distribution for each variable, in the same order they were put into the model. In this case, they represent the guest, prize, and monty variables respectively. We see that everything is equally likely.\n",
    "\n",
    "We can also pass in an array where `None` (or `np.nan`) correspond to the unobserved values."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([{\n",
       "    \"frozen\" :false,\n",
       "    \"dtype\" :\"str\",\n",
       "    \"class\" :\"Distribution\",\n",
       "    \"parameters\" :[\n",
       "        {\n",
       "            \"A\" :0.3333333333333333,\n",
       "            \"C\" :0.3333333333333333,\n",
       "            \"B\" :0.3333333333333333\n",
       "        }\n",
       "    ],\n",
       "    \"name\" :\"DiscreteDistribution\"\n",
       "},\n",
       "       {\n",
       "    \"frozen\" :false,\n",
       "    \"dtype\" :\"str\",\n",
       "    \"class\" :\"Distribution\",\n",
       "    \"parameters\" :[\n",
       "        {\n",
       "            \"A\" :0.3333333333333333,\n",
       "            \"C\" :0.3333333333333333,\n",
       "            \"B\" :0.3333333333333333\n",
       "        }\n",
       "    ],\n",
       "    \"name\" :\"DiscreteDistribution\"\n",
       "},\n",
       "       {\n",
       "    \"frozen\" :false,\n",
       "    \"dtype\" :\"str\",\n",
       "    \"class\" :\"Distribution\",\n",
       "    \"parameters\" :[\n",
       "        {\n",
       "            \"A\" :0.3333333333333333,\n",
       "            \"C\" :0.3333333333333333,\n",
       "            \"B\" :0.3333333333333333\n",
       "        }\n",
       "    ],\n",
       "    \"name\" :\"DiscreteDistribution\"\n",
       "}], dtype=object)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.predict_proba([None, None, None])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All of the variables that were observed will be the observed value, and all of the variables that were unobserved will be a `DiscreteDistribution` object. This means that `parameters[0]` will return the underlying dictionary used by the distribution.\n",
    "\n",
    "Now lets do something different, and say that the guest has chosen door 'A'. We do this by passing a dictionary to `predict_proba` with key pairs consisting of the name of the state (in the state object), and the value which that variable has taken, or by passing in a list where the first index is our observation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['A',\n",
       "       {\n",
       "    \"frozen\" :false,\n",
       "    \"dtype\" :\"str\",\n",
       "    \"class\" :\"Distribution\",\n",
       "    \"parameters\" :[\n",
       "        {\n",
       "            \"A\" :0.3333333333333333,\n",
       "            \"C\" :0.3333333333333333,\n",
       "            \"B\" :0.3333333333333333\n",
       "        }\n",
       "    ],\n",
       "    \"name\" :\"DiscreteDistribution\"\n",
       "},\n",
       "       {\n",
       "    \"frozen\" :false,\n",
       "    \"dtype\" :\"str\",\n",
       "    \"class\" :\"Distribution\",\n",
       "    \"parameters\" :[\n",
       "        {\n",
       "            \"A\" :0.0,\n",
       "            \"C\" :0.49999999999999983,\n",
       "            \"B\" :0.49999999999999983\n",
       "        }\n",
       "    ],\n",
       "    \"name\" :\"DiscreteDistribution\"\n",
       "}], dtype=object)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.predict_proba(['A', None, None])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can see that now Monty will not open door 'A', because the guest has chosen it. At the same time, the distribution over the prize has not changed, it is still equally likely that the prize is behind each door.\n",
    "\n",
    "Now, lets say that Monty opens door 'C' and see what happens. Here we use a dictionary rather than a list simply to show how one can use both input forms depending on what is more convenient."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array(['A',\n",
       "       {\n",
       "    \"frozen\" :false,\n",
       "    \"dtype\" :\"str\",\n",
       "    \"class\" :\"Distribution\",\n",
       "    \"parameters\" :[\n",
       "        {\n",
       "            \"A\" :0.3333333333333334,\n",
       "            \"C\" :0.0,\n",
       "            \"B\" :0.6666666666666664\n",
       "        }\n",
       "    ],\n",
       "    \"name\" :\"DiscreteDistribution\"\n",
       "},\n",
       "       'C'], dtype=object)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.predict_proba({'guest': 'A', 'monty': 'C'})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Suddenly, we see that the distribution over prizes has changed. It is now twice as likely that the car is behind the door labeled 'B'. This demonstrates that when on the game show, it is always better to change your initial guess after being shown an open door. Now you could go and win tons of cars, except that the game show got cancelled."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Imputation Given Structured Constraints\n",
    "\n",
    "The task of filling in an incomplete matrix can be called imputation, and there are many approaches for doing so. One of the most well known is that of matrix factorization, where a latent representation is learned for each of the columns and each of the rows such that the dot product between the two can reconstruct values in the matrix. Due to the manner that these latent representations are learned, the matrix does not need to be complete, and the dot product can then be used to fill in all of the missing values.\n",
    "\n",
    "One weakness of the matrix factorization approach is that constraints and known relationships can't be enforced between the features. A simple example is that the rule \"when column 1 is 'A' and column 2 is 'B', column 3 must be 'C'\" can potentially be learned in the representation, but can't be simply hard-coded like a conditional probability table would. A more complex example would say that a pixel in an image can be predicted from its neighbors, whereas the notion of neighbors is more difficult to specify for a factorization approach.\n",
    "\n",
    "The process for imputing data given a Bayesian network is to either first learn the structure of the network from the given data, or have a known structure, and then use loopy-belief propogation to predict the best values for the missing features.\n",
    "\n",
    "Let's see an example of this on the digits data set, binarizing the data based on the median value. We'll only use the first two rows because learning large, unconstrained Bayesian networks is difficult. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAPEAAAD1CAYAAACBWhMfAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMS4wLCBo\ndHRwOi8vbWF0cGxvdGxpYi5vcmcvpW3flQAADDxJREFUeJzt3X9M1fd+x/EXP0bChdGMVjiZO3M7\nSNMGHd2sw2qESIIcLhiIkKa2621JTVzS7CQFbECu3lwTNUuMf/jPMmLa4JZ1XW8MuPKnqDT1xwx6\nwx+YNg31Djc5jbqUHCke+Obsj5uYJde77/cg38/xbZ+Pv4Q/+LxM+/QcDl/ONy+TyWQEwKz8XA8A\n8GSIGDCOiAHjiBgwjogB44gYMK5wNb7I5OTkanwZAD42bdr0O59blYgl6a+37FqtL/XU+OUf73B6\nXu8/bnF21vfHfuXsrL+auuvsrGTqf5yd5dp/XPn3x36ep9OAcUQMGEfEgHFEDBhHxIBxRAwYR8SA\ncUQMGBco4omJCTU3N6upqUlDQ0NhbwKQBd+IPc/T4cOHderUKY2Njenzzz/XN99842IbgAB8I56a\nmtK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TCoSiTz6uLKy8pn5H/3/un37tm7evKna2tpcT1kVR48e1f79+5Wf/+y8jDI7\nO6vy8nINDAyoo6NDg4ODWlhYyPWsrDn/L/K4n2jl5eW5nhGqBw8eKJFI6MCBAyotLc31nCd2/vx5\nlZeXa8OGDbmesqqWl5c1PT2tPXv2aGRkRMXFxSZfo3EecSQS0dzc3KOPk8mkKioqXM8IzdLSkhKJ\nhHbt2vXMvJ3R9evXNT4+rsbGRvX09OjKlSvq6+vL9awnFolEFIlEHj1bisfjmp6ezvGq7DmPeOPG\njbp165ZmZ2eVTqc1NjamxsZG1zNCkclkNDg4qFgspu7u7lzPWTW9vb2amJjQ+Pi4Tpw4oS1btuj4\n8eO5nvXE1qxZo0gkopmZGUm/vTlCVVVVjldlz/mr04WFhTp06JD27t0rz/PU2dmp6upq1zNCMTk5\nqdHRUb344otqb2+XJPX09KihoSHHy/D7HDx4UH19fVpaWlI0GtWxY8dyPSlrXHYJGPfsvNQI/EgR\nMWAcEQPGETFgHBEDxhExYBwRA8YRMWDc/wJhO7cnwel5KgAAAABJRU5ErkJggg==\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7f9a52e76850>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from sklearn.datasets import load_digits\n",
    "\n",
    "data = load_digits()\n",
    "X, _ = data.data, data.target\n",
    "\n",
    "plt.imshow(X[0].reshape(8, 8))\n",
    "plt.grid(False)\n",
    "plt.show()\n",
    "\n",
    "X = X[:,:16]\n",
    "X = (X > numpy.median(X)).astype('float64')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now let's remove a large portion of the pixels randomly from each of the images. We can do that with numpy arrays by setting missing values to `np.nan`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.,  0.,  1., ...,  1.,  1.,  0.],\n",
       "       [ 0., nan, nan, ..., nan,  0.,  0.],\n",
       "       [ 0.,  0., nan, ...,  1.,  0.,  0.],\n",
       "       ...,\n",
       "       [ 0.,  0., nan, ...,  1.,  0., nan],\n",
       "       [ 0., nan, nan, ...,  1., nan,  0.],\n",
       "       [nan,  0.,  1., ..., nan,  0., nan]])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "numpy.random.seed(111)\n",
    "\n",
    "i = numpy.random.randint(X.shape[0], size=10000)\n",
    "j = numpy.random.randint(X.shape[1], size=10000)\n",
    "\n",
    "X_missing = X.copy()\n",
    "X_missing[i, j] = numpy.nan\n",
    "X_missing"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can set up a baseline for how good an imputation is by using the average pixel value as a replacement. Because this is binary data, we can use the mean absolute error to measure how good these approaches are on imputing the pixels that are not observed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/jmschr/anaconda2/lib/python2.7/site-packages/h5py/__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n",
      "Using Theano backend.\n",
      "WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0.1954958904004812"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from fancyimpute import SimpleFill\n",
    "\n",
    "y_pred = SimpleFill().fit_transform(X_missing)[i, j]\n",
    "numpy.abs(y_pred - X[i, j]).mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, we can see how good an IterativeSVD approach is, which is similar to a matrix factorization."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.26645818594371457"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from fancyimpute import IterativeSVD\n",
    "\n",
    "y_pred = IterativeSVD(verbose=False).fit_transform(X_missing)[i, j]\n",
    "numpy.abs(y_pred - X[i, j]).mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, we can try building a Bayesian network using the Chow-Liu algorithm and then use the resulting network to fill in the matrix."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.1092"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "y_hat = BayesianNetwork.from_samples(X_missing, max_parents=1).predict(X_missing)\n",
    "numpy.abs(numpy.array(y_hat)[i, j] - X[i, j]).mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can compare this to a better imputation approach, that of K-nearest neighbors, and see how good using a Bayesian network is."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.16290500020624946"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from fancyimpute import KNN\n",
    "\n",
    "y_pred = KNN(verbose=False).fit_transform(X_missing)[i, j]\n",
    "numpy.abs(y_pred - X[i, j]).mean()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Looks like in this case the Bayesian network is better than KNN for imputing the pixels. It is, however, slower than the fancyimpute methods."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The API\n",
    "\n",
    "### Initialization\n",
    "\n",
    "While the methods are similar across all models in pomegranate, Bayesian networks are more closely related to hidden Markov models than the other models. This makes sense, because both of them rely on graphical structures.\n",
    "\n",
    "The first way to initialize Bayesian networks is to pass in one distribution and state at a time, and then pass in edges. This is similar to hidden Markov models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "d1 = DiscreteDistribution({True: 0.2, False: 0.8})\n",
    "d2 = DiscreteDistribution({True: 0.6, False: 0.4})\n",
    "d3 = ConditionalProbabilityTable(\n",
    "        [[True,  True,  True,  0.2],\n",
    "         [True,  True,  False, 0.8],\n",
    "         [True,  False, True,  0.3],\n",
    "         [True,  False, False, 0.7],\n",
    "         [False, True,  True,  0.9],\n",
    "         [False, True,  False, 0.1],\n",
    "         [False, False, True,  0.4],\n",
    "         [False, False, False, 0.6]], [d1, d2])\n",
    "\n",
    "s1 = State(d1, name=\"s1\")\n",
    "s2 = State(d2, name=\"s2\")\n",
    "s3 = State(d3, name=\"s3\")\n",
    "\n",
    "model = BayesianNetwork()\n",
    "model.add_states(s1, s2, s3)\n",
    "model.add_edge(s1, s3)\n",
    "model.add_edge(s2, s3)\n",
    "model.bake()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The other way is to use the `from_samples` method if given a data set."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAOEAAAD5CAYAAADRNlKMAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDIuMS4wLCBo\ndHRwOi8vbWF0cGxvdGxpYi5vcmcvpW3flQAAIABJREFUeJztnXl8Tdfax3/75JxMRJOYSogYYs4N\nRVQ1pQRVakgHpWjLrbF61Xxf3E6ualWvovoqpUXrSod7UTSJeap6VShibAihNIaQeThnvX8siSDJ\n2XufPZy9z/P9fPrpIWs965dj//Zae+211iMwxhgIgtANi94CCMLTIRMShM6QCQlCZ8iEBKEzZEKC\n0BkyIUHoDJmQIHSGTEgQOkMmJAidIRMSh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xIEDpDJiQI\nnSETEoTOkAkJQmfIhAShM2RCgtAZMiFB6AyZkCB0hkxIEDpDJiQInSETEoTOkAkJQmf+H1qjhQtq\nPAd5AAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x7f9a0c475390>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "numpy.random.seed(111)\n",
    "\n",
    "X = numpy.random.randint(2, size=(15, 15))\n",
    "X[:,5] = X[:,4] = X[:,3]\n",
    "X[:,11] = X[:,12] = X[:,13]\n",
    "\n",
    "model = BayesianNetwork.from_samples(X)\n",
    "model.plot()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The structure learning algorithms are covered more in depth in the accompanying notebook.\n",
    "\n",
    "We can look at the structure of the network by using the `structure` attribute. Each tuple is a node, and the integers in the tuple correspond to the parents of the node."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "((),\n",
       " (10, 14),\n",
       " (9,),\n",
       " (1,),\n",
       " (3,),\n",
       " (4,),\n",
       " (7, 14),\n",
       " (0,),\n",
       " (0,),\n",
       " (),\n",
       " (),\n",
       " (6, 7),\n",
       " (11,),\n",
       " (12,),\n",
       " (0,))"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.structure"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Prediction\n",
    "\n",
    "The prediction method is similar to the other models. Inference is done using loopy belief propogation, which is an approximate version of the forward-backward algorithm that can be significantly faster while still precise. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([False, False, False, False, 0, 0, False, 1, False, 0, True, 1, 1,\n",
       "        True, False], dtype=object)]"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.predict([[False, False, False, False, None, None, False, None, False, None, True, None, None, True, False]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The predict method will simply return the argmax of all the distributions after running the `predict_proba` method. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([False, False, False, False,\n",
       "        {\n",
       "     \"frozen\" :false,\n",
       "     \"dtype\" :\"numpy.int64\",\n",
       "     \"class\" :\"Distribution\",\n",
       "     \"parameters\" :[\n",
       "         {\n",
       "             \"1\" :0.0,\n",
       "             \"0\" :1.0\n",
       "         }\n",
       "     ],\n",
       "     \"name\" :\"DiscreteDistribution\"\n",
       " },\n",
       "        {\n",
       "     \"frozen\" :false,\n",
       "     \"dtype\" :\"numpy.int64\",\n",
       "     \"class\" :\"Distribution\",\n",
       "     \"parameters\" :[\n",
       "         {\n",
       "             \"1\" :0.0,\n",
       "             \"0\" :1.0\n",
       "         }\n",
       "     ],\n",
       "     \"name\" :\"DiscreteDistribution\"\n",
       " },\n",
       "        False,\n",
       "        {\n",
       "     \"frozen\" :false,\n",
       "     \"dtype\" :\"numpy.int64\",\n",
       "     \"class\" :\"Distribution\",\n",
       "     \"parameters\" :[\n",
       "         {\n",
       "             \"1\" :0.5555555555555556,\n",
       "             \"0\" :0.44444444444444453\n",
       "         }\n",
       "     ],\n",
       "     \"name\" :\"DiscreteDistribution\"\n",
       " },\n",
       "        False,\n",
       "        {\n",
       "     \"frozen\" :false,\n",
       "     \"dtype\" :\"numpy.int64\",\n",
       "     \"class\" :\"Distribution\",\n",
       "     \"parameters\" :[\n",
       "         {\n",
       "             \"1\" :0.0,\n",
       "             \"0\" :1.0\n",
       "         }\n",
       "     ],\n",
       "     \"name\" :\"DiscreteDistribution\"\n",
       " },\n",
       "        True,\n",
       "        {\n",
       "     \"frozen\" :false,\n",
       "     \"dtype\" :\"numpy.int64\",\n",
       "     \"class\" :\"Distribution\",\n",
       "     \"parameters\" :[\n",
       "         {\n",
       "             \"1\" :1.0,\n",
       "             \"0\" :0.0\n",
       "         }\n",
       "     ],\n",
       "     \"name\" :\"DiscreteDistribution\"\n",
       " },\n",
       "        {\n",
       "     \"frozen\" :false,\n",
       "     \"dtype\" :\"numpy.int64\",\n",
       "     \"class\" :\"Distribution\",\n",
       "     \"parameters\" :[\n",
       "         {\n",
       "             \"1\" :1.0,\n",
       "             \"0\" :0.0\n",
       "         }\n",
       "     ],\n",
       "     \"name\" :\"DiscreteDistribution\"\n",
       " },\n",
       "        True, False], dtype=object)]"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.predict_proba([[False, False, False, False, None, None, False, None, False, None, \n",
    "                      True, None, None, True, False]])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.15"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
